package com.codebox.knowledge.keyboardview;

import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.PopupWindow;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.codebox.common.base.BaseActivity;
import com.codebox.common.common.RouterPath;
import com.codebox.common.util.LogUtils;
import com.codebox.knowledge.R;
import com.codebox.knowledge.databinding.ActivityCarNoBinding;
import com.parkingwang.keyboard.PopupKeyboard;

import java.lang.reflect.Method;

/**
 * 车牌号 自定义键盘
 *
 * @author Able
 */
@Route(path = RouterPath.KnowledgeRouterPath.PATH_CARDNO)
public class CarNoActivity extends BaseActivity<ActivityCarNoBinding> implements View.OnClickListener {

    private PopupWindow mPopWindow;
    private KeyboardView mKeyboardView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_no);

        initView();
        initListener();
    }

    private void initView() {
        disableShowSoftInput();
        setTitle("车牌号键盘");
        setNavigationIcon(R.drawable.ic_back);

        //-----------------------  使用第三方库实现  --------------
        // 创建弹出键盘
        PopupKeyboard mPopupKeyboard = new PopupKeyboard(this);
        // 弹出键盘内部包含一个KeyboardView，在此绑定输入两者关联。
        mPopupKeyboard.attach(mBinding.inputView, this);
        // KeyboardInputController提供一个默认实现的新能源车牌锁定按钮
        mPopupKeyboard.getController()
                .setDebugEnabled(true);
        //------------------------------------------------------

        initKeyBoard();
    }

    private void initListener() {
        mBinding.etCarNo.setOnClickListener(this);
        mBinding.etCarNo.addTextChangedListener(new MyTextWatcher(mBinding.etCarNo));
        mBinding.etCarNo.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus && v.getId() == R.id.et_car_no) {
//                showPopWindow();
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.et_car_no) {
            showPopWindow();
        }
    }

    /**
     * 禁止EditText弹出软键盘，光标依然正常显示。
     */
    public void disableShowSoftInput() {
        if (android.os.Build.VERSION.SDK_INT <= 10) {
            mBinding.etCarNo.setInputType(InputType.TYPE_NULL);
        } else {
            Class<EditText> cls = EditText.class;
            Method method;
            try {
                method = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                method.setAccessible(true);
                method.invoke(mBinding.etCarNo, false);
            } catch (Exception e) {
            }
            try {
                method = cls.getMethod("setSoftInputShownOnFocus", boolean.class);
                method.setAccessible(true);
                method.invoke(mBinding.etCarNo, false);
            } catch (Exception e) {
            }
        }
    }

    private void showPopWindow() {
        if (mPopWindow == null) {
            return;
        }
        if (!mPopWindow.isShowing()) {
            mPopWindow.showAtLocation(mBinding.getRoot(), Gravity.BOTTOM, 0, 0);
        }
    }


    private void initKeyBoard() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.view_keyboard, null);
        mKeyboardView = contentView.findViewById(R.id.keyboard_view);

        try {
            if (mBinding.etCarNo.getSelectionStart() == 0) {
                mKeyboardView.setKeyboard(new Keyboard(CarNoActivity.this, R.xml.province));
            } else {
                mKeyboardView.setKeyboard(new Keyboard(CarNoActivity.this, R.xml.letter));
            }
            mKeyboardView.setPreviewEnabled(false);
            mKeyboardView.setOnKeyboardActionListener(mOnKeyboardActionListener);
        } catch (Exception e) {
            LogUtils.e("initKeyBoard", "KeyboardView初始化失败");
        }

        if (mPopWindow == null) {
            mPopWindow = new PopupWindow(CarNoActivity.this);
        }
        mPopWindow.setContentView(contentView);
        mPopWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mPopWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopWindow.setBackgroundDrawable(null);
        mPopWindow.setOutsideTouchable(true);
    }


    private KeyboardView.OnKeyboardActionListener mOnKeyboardActionListener = new KeyboardView.OnKeyboardActionListener() {
        @Override
        public void onPress(int primaryCode) {
        }

        @Override
        public void onRelease(int primaryCode) {
        }

        @Override
        public void onKey(int primaryCode, int[] keyCodes) {
            LogUtils.e("onKey", "primaryCode:" + primaryCode);
            Editable editable = mBinding.etCarNo.getText();
            int start = mBinding.etCarNo.getSelectionStart();

            if (primaryCode == -10001 && start > 0) {
                editable.delete(start - 1, start);
            } else if (primaryCode == -10002) {
                mPopWindow.dismiss();
            }
        }

        @Override
        public void onText(CharSequence text) {
            Editable editable = mBinding.etCarNo.getText();
            int start = mBinding.etCarNo.getSelectionStart();
            editable.insert(start, text);
        }

        @Override
        public void swipeLeft() {
        }

        @Override
        public void swipeRight() {
        }

        @Override
        public void swipeDown() {
        }

        @Override
        public void swipeUp() {
        }
    };

    /**
     * EditText 监听
     * 通过判断字符个数，改变键盘内容
     */
    private class MyTextWatcher implements TextWatcher {
        private EditText editText;

        public MyTextWatcher(EditText editText) {
            this.editText = editText;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (editText.getSelectionStart() == 0) {
                mKeyboardView.setKeyboard(new Keyboard(CarNoActivity.this, R.xml.province));
            } else {
                mKeyboardView.setKeyboard(new Keyboard(CarNoActivity.this, R.xml.letter));
            }
        }
    }

}